import {useState, useEffect, useRef, forwardRef, useImperativeHandle} from 'react';
import {useNavigate, useSearchParams} from 'react-router-dom';
import PageTable from '@/components/PageTable.tsx';
import {findDicNameForDicCode, getDicOnCode} from '@/utils/dicAll.ts'
import DynamicSearchForm from '@/components/DynamicSearchForm/index.tsx'
import {deleteOrg, exportOrgInformation, logoutOrg, orgMoveSort,} from "@/axios/apis.ts"
import PageActionBar from "@/components/PageActionBar.tsx"
import {PlusOutlined} from "@ant-design/icons";
import type {MenuProps} from 'antd';
import {downloadFile} from "@/utils";
import {message, Dropdown, Button} from "antd";
import {AlignLeftOutlined} from '@ant-design/icons';
import {sessionSet} from "@/utils/storage.ts";

const OrganList = forwardRef((props, ref) => {
        useImperativeHandle(ref, () => ({
            queryList: () => {
                if (tableRef?.current) {
                    tableRef?.current.fetchData({}, {...searchForm, orgPathList: treeCode})
                }
            }
        }));
        const {searchForm, treeData, setSearchForm, treeCode, resetForm, initialValues} = props
        const navigate = useNavigate()
        // 强制更新
        const [searchFields] = useState({
            search: [
                {
                    type: 'input',
                    name: 'orgCode',
                    label: '机构代码',
                    placeholder: '请输入',
                },
                {
                    type: 'input',
                    name: 'orgName',
                    label: '机构名称',
                    placeholder: '请输入',
                },
                {
                    type: 'cascader',
                    name: 'orgSuperCode',
                    label: '直接上级',
                    placeholder: '请选择',
                    options: treeData,
                    fieldNames: {
                        label: 'orgName', value: 'orgCode', children: 'orgChildrenMap'
                    },
                },
            ],
            expand: [
                {
                    type: 'select',
                    name: 'orgClass',
                    label: '机构级别',
                    placeholder: '请选择',
                    options: getDicOnCode("SYS.ORGS"),
                },
                {
                    type: 'select',
                    name: 'status',
                    label: '机构状态',
                    placeholder: '请选择',
                    options: getDicOnCode("SYS.STATUS"),
                },
                {
                    type: 'select',
                    name: 'listingFlag',
                    label: '是否持牌',
                    placeholder: '请选择',
                    options: getDicOnCode("SYS.ISNOT"),
                },
            ]
        })
        const tableRef = useRef(null);
        const formRef = useRef(null);
        const [tableData, setTableData] = useState<[]>([]);
        const moveUpAndDown = (type: string, index: number, Oid: string) => {
            if (type === '上移') {
                if (index === 0) return message.error('已经是第一行数据，不能上移')
            } else if (type === '下移') {
                if (index + 1 >= tableData.length) return message.error('已经是最后一行数据，不能下移')
            }
            const Nid = type === '上移' ? tableData[index - 1].id : tableData[index + 1].id
            orgMoveSort({Oid, Nid}).then(res => {
                if (+res.code === 200) {
                    message.success('操作成功')
                    tableRef?.current.fetchData({}, {...searchForm, orgPathList: treeCode})
                } else {
                    message.error(`${type}失败`)
                }
            })
        }
        const items = [{
            key: 'logout',
            label: <Button color="default" variant="link">注销</Button>
        }, {
            key: 'delete',
            label: <Button color="default" variant="link">删除</Button>
        }]
        const DropdownClick = (key, record) => {
            if (key === 'logout') {
                if (record.status == '0') return false
                logoutOrg({id: record.id, orgPath: record.orgCode}).then(res => {
                    if (+res.code === 200) {
                        message.success('注销成功')
                        tableRef?.current.fetchData({}, {...searchForm, orgPathList: treeCode})
                    }
                })
            }else if (key === 'delete') {
                deleteOrg({id: record.id, orgCode: record.orgCode}).then(res => {
                    if (+res.code === 200) {
                        message.success('删除成功')
                        tableRef?.current.fetchData({}, {...searchForm, orgPathList: treeCode})
                    }
                })
            }
        }

        const columns = [
            {
                title: "序号",
                dataIndex: "index",
                key: "index",
                render: (_1, _2, index) => <>{index + 1}</>,
                width: 50
            },
            {
                title: '操作',
                key: 'action',
                render: (_, record) => (
                    <div className="table-options">
                    <span className="operation_style" onClick={() => {
                        const params = new URLSearchParams()
                        params.append('type', 'details')
                        sessionSet({key: 'organDetails', value: record})
                        navigate(`/organAdd?${params.toString()}`)
                    }}>明细</span>
                        <span className="operation_style" onClick={() => {
                            const params = new URLSearchParams()
                            params.append('type', 'edit')
                            sessionSet({key: 'organDetails', value: record})
                            navigate(`/organAdd?${params.toString()}`)
                        }}>修改</span>
                        <Dropdown menu={{items, onClick: ({key}) => DropdownClick(key, record)}} placement="bottom"
                                  arrow>
                            <AlignLeftOutlined />
                        </Dropdown>
                    </div>
                ),
                width: 120
            },
            {
                title: '排序',
                key: 'sort',
                render: (_, record, index) => (
                    <div className="table-options">
                        {[2, 3].includes(record.orders) &&
                            <span className="operation_style"
                                  onClick={() => moveUpAndDown('上移', index, record.id)}>上移</span>}
                        {[1, 3].includes(record.orders) &&
                            <span className="operation_style"
                                  onClick={() => moveUpAndDown('下移', index, record.id)}>下移</span>}
                    </div>
                ),
                width: 100
            },
            {
                title: "机构代码",
                dataIndex: "orgCode",
                key: "orgCode",
            },
            {
                title: "机构名称",
                dataIndex: "orgName",
                key: "orgName",
            },
            {
                title: "上级机构",
                dataIndex: "orgSuperName",
                key: "orgSuperName",
            }, {
                title: "机构级别",
                dataIndex: "orgClass",
                key: "orgClass",
                render: (value) => <>{findDicNameForDicCode('SYS.ORGS', value)}</>,
            }, {
                title: "机构状态",
                dataIndex: "status",
                key: "status",
                render: (value) => <>{findDicNameForDicCode('SYS.STATUS', value)}</>,
            }
        ];
        const handleSearch = (values: any) => {
            setSearchForm({...values, orgPathList: treeCode})
            if (tableRef?.current) {
                tableRef?.current.fetchData({}, {...searchForm, orgPathList: treeCode})
            }
        }
        const btnList = [
            {
                name: '新增',
                type: 'primary',
                icon: <PlusOutlined />,
                onClick: () => {
                    const params = new URLSearchParams()
                    params.append('type', 'add')
                    navigate(`/organAdd?${params.toString()}`)
                }
            },
            {
                name: '导出',
                onClick: () => {
                    exportOrgInformation(searchForm).then(res => {
                        downloadFile(res, '机构管理.csv')
                    })
                }
            },
        ]

        return (
            <>
                <DynamicSearchForm fields={searchFields} onSearch={handleSearch} ref={formRef}
                                   initialValues={initialValues}
                                   resetForm={resetForm} />
                <PageActionBar btnList={btnList} />
                <PageTable
                    columns={columns}
                    reqestUrl="queryConditionOrg"
                    searchForm={searchForm}
                    ref={tableRef}
                    pageNumKey="page"
                    pageSizeKey="total"
                    getData={(list: []) => setTableData(list)}
                />
            </>
        );
    }
)

export default OrganList;